<template>
  <common-list-group class="report-component-wrap">
    <div slot="group" class="group-list-component-wrap">
      <div class="group-header-wrap">
        <div class="group-header-title">数据集分类</div>
      </div>
      <common-tree
        ref="treeRef"
        :isRequest="isRequest"
        :treeLoading="treeLoading"
        :is-slot="true"
        :tree-data="groupTreeData"
        :treeProp="{ isLeaf: 'leaf' }"
        search-placeholder="查询分类"
        :hiddenIndexIcon="3"
        :current-node-key="currentNodeKey"
        setNodeByKey="leaf"
        isShowIconForNoChild
        @handleNodeClick="handleNodeClick"
      >
        <div slot-scope="{ scope }" class="tree-item-wrap">
          <common-carousel-text :content="scope.data.name" :font-size="14" />
          <el-popover
            v-if="scope.data.isDefault === 0"
            popper-class="chart-type-list-popover"
            placement="right-start"
            width="150"
            trigger="hover"
          >
            <!--            <i slot="reference" class="iconfont icon-more"></i>-->
            <commonIcon
              iconName="icon-more"
              slot="reference"
              iconType="icon"
              :iconSize="16"
            ></commonIcon>
            <common-menu>
              <common-menu-item
                v-if="scope.node.level < 3"
                v-has-permi="['system:datesettype:add']"
                @click="treeAdd(scope.data)"
                >新增子分类
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                v-has-permi="['system:datesettype:edit']"
                @click="treeEdit(scope.data)"
                >编辑
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                v-has-permi="['system:datesettype:remove']"
                @click="handleDeleteTree(scope.data.id)"
                >删除
              </common-menu-item>
            </common-menu>
          </el-popover>
        </div>
      </common-tree>
    </div>
    <common-edit-dialog
      :title="`${isTypeEdit ? '编辑分类' : '新增分类'}`"
      :visible="isTypeDialog"
      :button-loading="dialogLoading"
      @cancel="typeDialogCancel"
      @submit="persistenceTypeForm"
      width="25%"
    >
      <el-form
        ref="typeForm"
        :model="typeForm"
        :rules="typeRule"
        label-width="80px"
        @submit.native.prevent
      >
        <el-form-item label="分类名称" prop="name">
          <common-input :maxlength="16" v-model="typeForm.name"></common-input>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
    <!-- <el-card> -->
    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="数据库类型" prop="datasourceType">
          <el-select v-model="query.datasourceType">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="ES" value="ES"></el-option>
            <el-option label="MYSQL" value="MYSQL"></el-option>
            <el-option label="API" value="API"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <common-input v-model="query.name" clearable @enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="query.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="有效" value="0"></el-option>
            <el-option label="无效" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 头部搜素end -->

    <!-- 按钮部门start -->
    <el-row :gutter="10" class="mb8" slot="tools" v-if="!predefined">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="hasType"
          @click="add(null)"
          v-has-permi="['system:dataset:add']"
          plain
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          :disabled="!showBatch"
          v-has-permi="['system:dataset:remove']"
          @click="handleDelete()"
          >批量删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 按钮部门end -->

    <!--列表 start-->
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="名称"
        align="left"
        prop="name"
        show-overflow-tooltip
        fixed
      ></el-table-column>
      <el-table-column label="数据库类型" align="left" prop="datasourceType" />
      <!-- <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        width="180"
        show-overflow-tooltip
      /> -->
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status === 0">有效</el-tag>
          <el-tag type="danger" v-if="row.status === 1">无效</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        label="描述"
        align="left"
        prop="remark"
        show-overflow-tooltip
      /> -->
      <!--      <el-table-column label="节点数量" align="left" prop="nodeNum" />-->
      <el-table-column label="操作" align="left" width="200" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handlePreview(row)">预览</el-button>
          <el-button type="text" @click="edit(row, false)">详情</el-button>
          <el-button
            type="text"
            v-if="!predefined"
            v-has-permi="['system:dataset:editDatasetType']"
            @click="branch(row)"
            >分类
          </el-button>
          <el-button
            type="text"
            v-if="($route.query.super_dev === 'true' && isAdmin) || !predefined"
            v-has-permi="['system:dataset:edit']"
            @click="edit(row, true)"
            >编辑
          </el-button>
          <el-button
            type="text"
            v-if="!predefined"
            v-has-permi="['system:dataset:remove']"
            @click="handleDelete(row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <preview ref="preview" v-if="preview" @back="preview = false"></preview>

    <template v-if="isShowAdd">
      <add-data-set
        ref="addDataSet"
        :departmentList="departmentList"
        :typeId="typeId"
        :typeName="typeName"
        :globalList="globalList"
        @refresh="getList"
        @close="closeAdd"
      ></add-data-set>
    </template>

    <common-edit-dialog
      title="切换分类"
      width="25%"
      :visible="isShowTypeListDialog"
      :button-loading="typeLoading"
      @cancel="updateTypeDialogCancel"
      @submit="updateTypeSubmit"
    >
      <el-form
        ref="updateTypeForm"
        :model="updateTypeForm"
        :rules="updateTypeRule"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="type">
          <el-cascader
            style="width: 100%"
            v-model="updateTypeForm.type"
            :show-all-levels="false"
            :options="typeList"
            :props="props"
            clearable
          >
            <template slot-scope="{ node, data }">
              <common-carousel-text :content="data.name"></common-carousel-text>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
  </common-list-group>
</template>
<script>
import BaseList from "@/mixins/BaseList";
import AddDataSet from "./components/add";
import Preview from "./components/preview";
import JsPlumb from "@/components/JsPlumb/index";
import {
  querytree,
  treeAdd,
  treeEdit,
  treeDelete,
  deleteCheck,
  getDataSetList,
  remove,
  getInfo,
  queryAllTree,
  editDatasetType,
  getPreviewReportsData,
  deleteForCheck,
  getDataSourceList,
  queryComponentInfo,
} from "@/api/screenConfig/dataSet";
import { classIfication } from "@/api/screenConfig/viewboard";
import { globalList } from "@/api/screenConfig/global";
import { getSingleArray, getFullDept } from "@/utils/util";
import { mapGetters } from "vuex";
import commonIcon from "@/components/CommonIcon";

export default {
  name: "index",
  mixins: [BaseList],
  components: {
    AddDataSet,
    Preview,
    JsPlumb,
    commonIcon,
  },
  data() {
    return {
      isRequest: false,
      treeLoading: false,
      multiple: true,
      predefined: false,
      esInputConfig: false,
      isTypeEdit: false,
      isTypeDialog: false,
      mySqlInputConfig: false,
      fieldConfig: false,
      variableConfig: false,
      preview: false,
      isShowAdd: false,
      list: [],
      typeName: "",
      loading: false,
      dialogLoading: false,
      typeForm: {
        id: null,
        name: "",
        parentId: 0,
        status: null,
        deptId: null,
      },
      typeRule: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        // deptId: [
        //   { required: true, message: '请选择组织', trigger: 'blur' }
        // ],
      },
      query: {
        id: "0",
        name: "",
        isDefault: 0,
        datasourceType: null,
        status: null,
        deptIds: null,
        pageNum: 1,
        pageSize: 10,
        classType: 0,
      },
      total: 0,
      groupTreeData: [],
      typeId: "", //数据集分类id
      currentNodeKey: "0",
      isShowTypeListDialog: false,
      typeLoading: false,
      typeList: [], //分类列表树形结构
      updateTypeForm: {
        id: null,
        type: null,
      },
      updateTypeRule: {
        typeId: [{ required: true, message: "请选择分类", trigger: "blur" }],
      },
      props: {
        checkStrictly: true,
        label: "name",
        value: "id",
        emitPath: false,
      },
      currentParent: 1,
      singleDeptList: [],
      globalList: [], //全局变量
      dataSourceList: [], //数据源列表
      departmentList: [],
    };
  },
  computed: {
    ...mapGetters(["isAdmin"]),
    hasType: function () {
      return (this.typeId ?? "") === "";
    },
  },
  methods: {
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },
    // 查询
    handleQuery() {
      this.query.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
    },

    // 树节点返回
    typeDialogCancel() {
      this.isTypeDialog = false;
    },
    // 树节点提交
    persistenceTypeForm() {
      this.$refs.typeForm.validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (this.isTypeEdit) {
            treeEdit(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("重命名成功");
                  this.isTypeDialog = false;
                  this.queryAllTree();
                } else {
                  this.$GlobalErrorConfirm("重命名失败", res.msg);
                }
              })
              .finally(() => (this.dialogLoading = false));
          } else {
            treeAdd(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.isTypeDialog = false;
                  this.queryAllTree();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => (this.dialogLoading = false));
          }
        }
      });
    },
    // /**
    //  * 获取数据源列表信息
    //  */
    // getDataSourceList() {
    //   getDataSourceList({ status: 0 }).then((res) => {
    //     if (res && res.code === 200) {
    //       this.dataSourceList = res.rows
    //     } else {
    //       this.dataSourceList = []
    //     }
    //   })
    // },
    /**
     * 获取全局变量配置数据
     */
    getGlobalList() {
      globalList({}).then((res) => {
        if (res && res.code === 200) {
          this.globalList = res.rows.reduce((r, c) => {
            r.push({
              id: c.id,
              name: c.name,
              type: c.type,
              defaultValue: c.defaultValue,
              variableType: "全部",
            });
            return r;
          }, []);
        } else {
          this.globalList = [];
        }
      });
    },
    handleNodeClick(info) {
      this.predefined = info.data.isDefault === 1;
      this.typeId = info.data.id;
      this.query.id =
        info.data.name === "自定义" || info.data.name === "预定义"
          ? "0"
          : info.data.id;
      this.query.isDefault = info.data.isDefault;
      this.typeName = info.data.name;
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      this.getList();
    },
    handlePreview(row) {
      this.preview = true;
      // console.log(row)
      this.$nextTick(() => {
        this.$refs.preview.getDataSetData(row, row.status !== 1);
      });
    },
    add() {
      this.isShowAdd = true;
      // this.$nextTick(() => {
      //   this.$refs.addDataSet.getGlobalList();
      // });
    },
    edit(row, isTrue) {
      if (!isTrue) {
        this.isShowAdd = true;
        this.$nextTick(() => {
          this.$refs.addDataSet.initData(row, isTrue);
        });
      } else {
        queryComponentInfo({ id: row.id }).then((res) => {
          if (res && res.code === 200) {
            if (res.data.length) {
              if (this.isAdmin) {
                this.$GlobalDeleteConfirm(
                  `该数据集已被${res.data.length}个组件关联，如若修改，已关联组件会损坏需重新配置。确认修改吗？`
                )
                  .then(() => {
                    this.isShowAdd = true;
                    this.$nextTick(() => {
                      this.$refs.addDataSet.initData(row, isTrue);
                    });
                  })
                  .catch(() => {});
              } else {
                this.$GlobalErrorConfirm(
                  "编辑失败",
                  `该数据集已被${res.data.length}个组件关联，请联系管理员修改！`
                );
              }
            } else {
              this.isShowAdd = true;
              this.$nextTick(() => {
                this.$refs.addDataSet.initData(row, isTrue);
              });
            }
          }
        });
      }
    },
    //分类
    branch(row) {
      this.isShowTypeListDialog = true;
      this.updateTypeForm.id = row.id;
      this.updateTypeForm.type = row.type;
    },
    //关闭更新分类弹窗
    updateTypeDialogCancel() {
      this.isShowTypeListDialog = false;
    },
    //更新分类
    updateTypeSubmit() {
      this.$refs.updateTypeForm.validate((valid) => {
        if (valid) {
          this.typeLoading = true;
          editDatasetType(this.updateTypeForm)
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("编辑分类成功");
                this.updateTypeDialogCancel();
                this.getList();
              } else {
                this.$GlobalErrorConfirm("编辑分类失败", res.msg);
              }
            })
            .finally(() => (this.typeLoading = false));
        }
      });
    },
    treeAdd(row) {
      //树节点新增
      this.typeForm.name = "";
      this.typeForm.remark = "";
      this.typeForm.id = "";
      this.typeForm.parentId = row.id ? row.id : 0;
      this.isTypeDialog = true;
      this.isTypeEdit = false;
    },
    treeEdit(row) {
      //树节点重命名
      this.isTypeDialog = true;
      this.isTypeEdit = true;
      this.typeForm.id = row.id;
      this.typeForm.parentId = row.parentId;
      this.typeForm.name = row.name;
      this.typeForm.deptId = row.deptId;
    },
    deleteTreeData(id) {
      // 树节点删除
      this.$GlobalDeleteConfirm()
        .then(() => {
          treeDelete({ id: id })
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("删除成功");
                this.queryAllTree();
              } else {
                this.$GlobalErrorMessage("删除失败");
              }
            })
            .finally(() => {
              this.queryAllTree();
            });
        })
        .catch(() => {});
    },

    /**
     * 左侧树形通用删除前校验方法
     */
    beforeDeleteTreeForCheck(id) {
      return new Promise((resolve, reject) => {
        deleteCheck({ id: id })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    deleteChildren(treeData) {
      if (!treeData.length) {
        return;
      }
      treeData.forEach((item) => {
        if (item.children && item.children.length) {
          this.deleteChildren(item.children);
        } else {
          delete item.children;
        }
      });
    },

    closeAdd() {
      this.isShowAdd = false;
    },
    //删除数据集
    deleteData(row) {
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          remove({ ids }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.query.pageNum > 1 &&
                ids.split(",").length === this.list.length
              ) {
                this.query.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //数据集列表
    getList() {
      this.loading = true;
      this.isRequest = true;
      getDataSetList(this.query)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows;
            this.list.forEach(
              (item) => (item.deptName = this.getDeptName(item.deptId || ""))
            );
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
          this.isRequest = false;
        });
    },
    // 查询树列表
    queryAllTree() {
      this.treeLoading = true;
      queryAllTree({ classType: 0 })
        .then((res) => {
          if (res && res.code === 200) {
            this.groupTreeData = [
              {
                id: "0-0",
                name: "预定义", // 名称
                isDefault: 1, // 1 预定义 0 自定义
                isRoot: true,
                leaf: false, // false 分类 true 数据集
                children: res.data.filter((item) => item.isDefault === 1),
              },
              {
                id: "0",
                name: "自定义",
                isDefault: 0,
                leaf: false,
                isRoot: true,
                children: res.data.filter((item) => item.isDefault === 0),
              },
            ];
            this.typeList = [this.groupTreeData[1]];
            this.deleteChildren(this.typeList);
            this.typeName = "自定义";
            this.typeId = "0";
            this.getList();
          } else {
            this.groupTreeData = [];
            this.typeList = [];
            this.handleListTips(res);
          }
        })
        .finally(() => (this.treeLoading = false));
    },
  },
  mounted() {
    // this.formData = JSON.stringify(this.formData)

    this.getGlobalList();
    this.queryAllTree();
    // this.getDataSourceList()
  },
};
</script>

<style scoped lang="scss">
.report-component-wrap {
  .tree-item-wrap {
    display: flex;
    align-items: center;
    width: 100%;

    &:hover {
      .iconfont {
        opacity: 1;
      }
    }

    .iconfont {
      opacity: 0;
      transition: opacity 0.15s linear;
    }

    .tree-label {
      margin-right: 4px;
    }

    .pre-icon {
      width: 12px;
      height: 12px;
      font-size: 12px;
    }
  }

  .group-header-wrap {
    height: 32px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-header-title {
      font-size: 14px;
    }
  }
}
</style>
